package com.stars.pao.aicloud.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stars.pao.aicloud.entity.Answer;
import com.stars.pao.aicloud.entity.enums.AiModelEnum;
import com.stars.pao.aicloud.entity.enums.AiTypeEnum;
import com.stars.pao.aicloud.service.IAnswerService;
import com.stars.pao.aicloud.util.AppVariable;
import com.stars.pao.aicloud.util.ResponseEntity;
import com.stars.pao.aicloud.util.SecurityUtil;
import com.stars.pao.aicloud.util.idempotent.Idempotent;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Tag(name = "豆包大模型控制器")
@RestController
@RequestMapping("/doubao")
public class DoubaoController {
    @Value("${doubao.api-key}")
    private String apiKey;
    @Value("${doubao.url}")
    private String url;
    @Value("${doubao.model_id}")
    private String modelId;
    @Resource
    private IAnswerService answerService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Idempotent
    // 调用对话
    @PostMapping("/chat")
    public ResponseEntity chat(String question)
    {
        if(!StringUtils.hasLength(question)) {
            ResponseEntity.fail("问题不能为空");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.DOUBAO.getValue(),
                AiTypeEnum.CHAT.getValue());
        String result = ""; // 大模型返回的结构
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResponseEntity.fail("请勿频繁请求，请稍后再试");
            }
            // 1.api-key + 调用 url 地址
            ArkService service = ArkService.builder().apiKey(apiKey)
                    .baseUrl(url).build();
            // 2.构建问题对象
            List<ChatMessage> messages = new ArrayList<>();
            messages.add(ChatMessage.builder()
                    .role(ChatMessageRole.USER)
                    .content(question)
                    .build());
            // 3.创建对象进行对话
            ChatCompletionRequest request = ChatCompletionRequest.builder()
                    .model(modelId) // 接入点的id（并不是大模型名字）!!!!
                    .messages(messages)
                    .build();
            // 4.得到对话的结果
            result = service.createChatCompletion(request)
                    .getChoices()
                    .get(0) // 获取 AI 大模型生成的第一条消息
                    .getMessage()
                    .getContent().toString();
            // 将对话信息存储到数据库
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.DOUBAO.getValue());
            answer.setUid(uid);
            answer.setType(AiTypeEnum.CHAT.getValue());
            isSave = answerService.save(answer);
        } catch (Exception e) {
        } finally {
            // 释放锁
            rLock.unlock();
        }
        if (isSave) {
            return ResponseEntity.succ(result);
        }
        return ResponseEntity.fail("请求操作失败，请重试！");
    }
    // 查询历史记录
    // 调用豆包历史对话查询记录
    @PostMapping("/getChatList")
    public ResponseEntity getChatList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int model = AiModelEnum.DOUBAO.getValue();
        int type = AiTypeEnum.CHAT.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model,type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if(list == null) {
            QueryWrapper<Answer> wrapper = new QueryWrapper<>();
            wrapper.eq("uid", uid);
            wrapper.eq("type", type);
            wrapper.eq("model", model);
            wrapper.orderByDesc("aid");
            List<Answer> dataList = answerService.list(wrapper);
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResponseEntity.succ(dataList);
        }else {
            return ResponseEntity.succ(list);
        }
    }
}
